#include "passworddialog.h"
#include "ui_passworddialog.h"
#include <QCryptographicHash>
#include <QApplication>
#include <QMessageBox>

PasswordDialog::PasswordDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::PasswordDialog)
    , authenticated(false)
{
    ui->setupUi(this);
    
    // 创建设置对象
    settings = new QSettings("ToyFactory", "OA", this);
    
    // 连接信号和槽
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &PasswordDialog::onOkClicked);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &PasswordDialog::onCancelClicked);
    
    // 加载密码
    loadPassword();
}

PasswordDialog::~PasswordDialog()
{
    delete ui;
}

bool PasswordDialog::isAuthenticated() const
{
    return authenticated;
}

void PasswordDialog::loadPassword()
{
    // 如果没有设置密码，则使用默认密码"admin123"
    correctPassword = settings->value("security/password", 
        QCryptographicHash::hash("admin123", QCryptographicHash::Sha256).toHex()).toString();
}

bool PasswordDialog::verifyPassword(const QString &inputPassword)
{
    // 对输入密码进行哈希处理并与存储的密码比较
    QString hashedInput = QCryptographicHash::hash(inputPassword.toUtf8(), QCryptographicHash::Sha256).toHex();
    return hashedInput == correctPassword;
}

void PasswordDialog::onOkClicked()
{
    QString inputPassword = ui->passwordEdit->text();
    if (inputPassword.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入密码");
        return;
    }
    
    if (verifyPassword(inputPassword)) {
        authenticated = true;
        accept();
    } else {
        QMessageBox::warning(this, "错误", "密码错误");
        ui->passwordEdit->clear();
        ui->passwordEdit->setFocus();
    }
}

void PasswordDialog::onCancelClicked()
{
    reject();
}